package com.youdianstar.app.ui

import android.app.Activity
import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.databinding.ActivityReportFaultBinding
import com.youdianstar.app.common.*
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.entity.FileUpResult
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.EditUtil
import com.youdianstar.app.common.util.LogUtil
import com.youdianstar.app.common.util.StrUtil
import com.youdianstar.app.common.util.dialog.DialogUtil
import com.youdianstar.app.common.widget.adapter.MultiPicAdapter
import com.youdianstar.app.common.auko.startActivity
import com.youdianstar.app.common.auko.startActivityForResult

import com.google.common.base.Joiner
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: ReportFaultActivity
 * Author: 82149 Create: 2021/10/28 16:04
 * Changes (from 2021/10/28)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class ReportFaultActivity : BaseActivity<ActivityReportFaultBinding, ReportViewModel>() {
    override fun layoutId(): Int = R.layout.activity_report_fault

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): ReportViewModel {
        val model: ReportViewModel by viewModel()
        return model
    }

    var orderNo = ""
    val REQUEST_CODE = 0x19

    //图片选择
    private var selectType: Int = 0
    var picAdapter: MultiPicAdapter? = null
    var imageList = mutableListOf<String>()

    //问题多选拼接
    lateinit var boxImageList : List<ImageView>
    lateinit var clickLayoutList : List<LinearLayout>
    private var checkboxStates = mutableListOf<String>()

    override fun initViewLayout() {
        super.initViewLayout()
        mBinding.headBar.initTitle(this, getString(R.string.home_reportFaultPB), showInner = false)

        EditUtil.setEditSpaceFilter(mBinding.edtContent)
        mBinding.edtContent.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                mBinding.tvCount.text = "${s.toString().length ?: 0}/300"
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }
        })

        initImageAction()
    }

    override fun initData() {
        super.initData()
        val order = intent.getStringExtra(Extra.IT_ORDERNO)
        order?.let {
            orderNo = it
        }
         boxImageList = listOf(
            mBinding.bxOthers,mBinding.bxCable, mBinding.bxTip,
            mBinding.bxCharge, mBinding.bxIndicator
        )
        clickLayoutList = listOf(
            mBinding.llOthers,mBinding.llCable, mBinding.llTip,
            mBinding.llCharge, mBinding.llIndicator
        )
        checkboxStates.clear()
        refreshBoxUI()
    }

    override fun initClickEvent() {
        clickLayoutList.forEach {
            it.setOnClickListener { lay->
                for ((index, v) in clickLayoutList.withIndex()) {
                    if (v.id == lay.id){
                        if (checkboxStates.contains(index.toString())){
                            checkboxStates.remove(index.toString())
                        } else
                            checkboxStates.add(index.toString())
                    } //多选模式
                }
                refreshBoxUI()
            }
        }

        mBinding.ivReportScan.setThrottleListener {
            //跳转扫码
            startActivityForResult<ScanActivity>(REQUEST_CODE,Extra.IT_TYPE to BisType.Scan_Report)
        }

        mBinding.btnConfirm.setThrottleListener {

            if (checkboxStates.isEmpty()){
                toastShow(getString(R.string.toast_selOption))
                return@setThrottleListener
            }

            val snoText = mBinding.edtSno.text.toString().trim()
            if (StrUtil.isEmpty(snoText)){
                toastShow(getString(R.string.toast_enterStationID))
                return@setThrottleListener
            }

            val etText = mBinding.edtContent.text.toString().trim()
            if (StrUtil.isEmpty(etText)){
                toastShow(getString(R.string.toast_requiredReport))
                return@setThrottleListener
            }

            if (imageList.isEmpty()){
                toastShow(getString(R.string.toast_requiredPhoto))
                return@setThrottleListener
            }

            mViewModel.reportFault(
                com.youdianstar.app.entity.ReportFaultyReq(
                    Joiner.on(",").join(checkboxStates), description = etText,
                    Joiner.on(",").join(imageList), orderNo = orderNo, cabinetNo = snoText
                )
            )
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.fileDeleteLiveData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
            }
        })

        mViewModel.fileUpLoadLiveData.observe(this,object : BaseApiResultObserver<FileUpResult>(false){
            override fun onDataResult(data: FileUpResult?) {
                super.onDataResult(data)
                dismissDialog()
                data?.let {
                    LogUtil.i("----add ="+it.value)
                    imageList.add(it.value)
                    picAdapter?.refreshData(imageList)
                    mBinding.tvPicCount.text = imageList.size.toString()+"/3"
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })

        mViewModel.reportResultLiveData.observe(this,object : BaseApiResultObserver<Any>(true){
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                startActivity<ReportResultActivity>(Extra.IT_TYPE to BisType.Report_OrderFault)
                finish()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })
    }

    /*设置CheckBox样式*/
    private fun refreshBoxUI(){
        for ((index, image) in boxImageList.withIndex()){
            image.setImageResource(if (checkboxStates.contains(index.toString())) R.mipmap.box_multi_selected else R.mipmap.box_multi_unselected)
        }
        for ((index, lg) in clickLayoutList.withIndex()){
            lg.setBackgroundResource(if (checkboxStates.contains(index.toString())) R.drawable.bg_report_selected else R.drawable.bg_report_unselected)
        }
    }

    private fun initImageAction() {
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        mBinding.rcyPic.layoutManager = linearLayoutManager

        picAdapter = MultiPicAdapter(this, 3,mutableListOf<String>(), object : MultiPicAdapter.OnPicSelect {
            override fun onAdd() {
                showPhotoDialog()
            }

            override fun onDelete(index: Int) {
                if (imageList.isEmpty().not() && index <= imageList.size - 1) {
                    mViewModel.deleteImage(imageList[index])
                    imageList.removeAt(index)
                    picAdapter?.refreshData(imageList)
                    mBinding.tvPicCount.text = imageList.size.toString()+"/3"
                }
                //标记 bt 不可点
//                if (imageList.isEmpty())
//                    mViewModel.enableBtEvent.postValue(false)
            }
        })
        mBinding.rcyPic.adapter = picAdapter
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            val sno = data?.getStringExtra(Extra.IT_SNO)
            sno.let {
                mBinding.edtSno.setText(it)
            }
        }
    }

    /*******************************图片选择部分************************************/

    /**图片选择器*/
    private fun showPhotoDialog() {
        DialogUtil.instance.showSelectDialog(this) { selectIndex ->
            selectType = selectIndex
            when (selectIndex) {
                PHOTO_CAMERA -> requestCameraPermission {
                    showPhotoPicker(PHOTO_CAMERA)
                }
                PHOTO_ALBUM -> requestAlbumPermission {
                    showPhotoPicker(PHOTO_ALBUM)
                }
            }
        }
    }

    /**
     * 调用-ImagePicker
     * @param type
     */
    private fun showPhotoPicker(type: Int) {
        startSLImagePicker(this, type = type, needCrop = false) { path ->
            mViewModel.upLoadImage(path)
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        super.onPermissionsGranted(requestCode, perms)
        if (requestCode == REQUEST_PERMISSION_CODE)
            showPhotoPicker(selectType)
    }

}